import { createSlice, PayloadAction } from "@reduxjs/toolkit";

interface CounterState {
  token: string;
  historySearchValue: string[];
}

let initialState: CounterState = {
  token: "",
  historySearchValue: [],
};

const counterSlice = createSlice({
  name: "counter",
  // 声明初始状态
  initialState,
  // 修改数据的同步方法
  reducers: {
    setToken: (state, { payload }: PayloadAction<string>) => {
      state.token = "Bearer" + " " + payload;
      localStorage.setItem("token", state.token);
    },
    setHistorySearchValue: (state, { payload }: PayloadAction<string>) => {
      if (state.historySearchValue.length >= 7) {
        let shiftArray = state.historySearchValue.slice(1);
        state.historySearchValue = [...shiftArray, payload];
      } else {
        state.historySearchValue = [...state.historySearchValue, payload];
      }
      localStorage.setItem(
        "search_history",
        JSON.stringify(state.historySearchValue)
      );
    },
    setLocalStroageValue: (state, { payload }: PayloadAction<string>) => {
      if (payload) {
        state.historySearchValue = [...JSON.parse(payload)];
      }
      return;
    },
  },
});

// 导出方法
const { setToken, setHistorySearchValue, setLocalStroageValue } =
  counterSlice.actions;
export { setToken, setHistorySearchValue, setLocalStroageValue };
// 导出reducer
const counterRudecer = counterSlice.reducer;
export default counterRudecer;
